/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
private:
    bool maze[500 + 5][500 + 5];
    bool visited[500 + 5];
    void bianli(TreeNode* root){
        if(!root)return;
        if(root->left){
            maze[root->val][root->left->val] = maze[root->left->val][root->val] = true;
            bianli(root->left);
        }
        if(root->right){
            maze[root->val][root->right->val] = maze[root->right->val][root->val] = true;
            bianli(root->right);
        }
    }
public:
    vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
        if(!k)return vector<int>(1, target->val);

        memset(maze, false, sizeof(maze));
        memset(visited, false, sizeof(visited));
        bianli(root);
        vector<int>ans;
        queue<int> p, q;
        q.push(target->val);
        visited[target->val] = true;
        while(k--){
            while(!q.empty()){
                p.push(q.front());
                q.pop();
            }
            while(!p.empty()){
                int temp = p.front();
                p.pop();
                for(int i = 0; i <= 500; i++){
                    if(maze[temp][i] && !visited[i]){
                        q.push(i);
                        visited[i] = true;
                    }
                }
            }
        }
        while(!q.empty()){
            ans.push_back(q.front());
            q.pop();
        }
        return ans;
    }
};

//2021/7/28 
